<template>
    <el-card class="card-bottom">
        <el-form :model="queryInfo.form" :inline="true" label-width="80px">
            <el-form-item label="账号">
                <el-input clearable v-model="queryInfo.form.username" class="width-180" placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input clearable v-model="queryInfo.form.phoneNumber" class="width-180" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="Email">
                <el-input clearable v-model="queryInfo.form.email" class="width-180" placeholder="请输入Email"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getUserList">搜索</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card>
        <el-row>
            <el-col :span="12">
                <p style="font-size: 18px;">用户列表</p>
            </el-col>
            <el-col :span="12">
                <div style="float:right;">
                    <el-button type="primary" @click="handleClick(1 , null)">添加</el-button>
                </div>
            </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-table :header-cell-style="{ background: '#FFFFFF', color: '#000000' }" :data="dataInfo.userDataArray" stripe
            style="width: 100%">
            <el-table-column type="selection" />
            <el-table-column fixed align="center" prop="userId" label="ID"/>
            <el-table-column fixed align="center" width="150" prop="username" label="用户名"/>
            <el-table-column align="center" prop="headImage" label="头像">
                <template #default="scope">
                    <div style="display: flex; align-items: center;">
                        <el-image 
                        style="width: 60px; height: 60px;" 
                        :src="scope.row.headImage"
                        :preview-src-list="[scope.row.headImage]" 
                        :hide-on-click-modal="true"
                        :preview-teleported="true">
                        </el-image>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="realName" label="真实姓名"/>
            <el-table-column width="160" align="center" prop="roleList" label="角色">
                <template #default="scope">
                    <div v-if="scope.row.superAdmin">
                        <el-tag effect="dark" type="success">超级管理员</el-tag>
                    </div>
                    <div v-else>
                        <el-tag style="margin-right: 2px;" 
                        v-for="item in scope.row.roleList" 
                        :key="item.roleId" 
                        effect="dark" 
                        type="success">
                            {{ item.roleName }}
                        </el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="userStatus" label="用户状态">
                <template #default="scope">
                    <el-tag v-if="scope.row.userStatus == 1" effect="dark" type="success">正常</el-tag>
                    <el-tag v-else-if="scope.row.userStatus == 2" effect="dark" type="danger">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column width="150" align="center" prop="phoneNumber" label="手机号"/>
            <el-table-column width="200" align="center" prop="email" label="Email"/>

            <el-table-column width="200" align="center" prop="createTime" label="创建时间" />
            <el-table-column width="200" align="center" prop="updateTime" label="更新时间"/>
            <el-table-column align="center" fixed="right" label="操作" width="160">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleClick(2 , scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.userStatus == 1" link type="primary" size="small" @click="handleClick(3 , scope.row)">禁用</el-button>
                    <el-button v-if="scope.row.userStatus == 2" link type="primary" size="small" @click="handleClick(3 , scope.row)">启用</el-button>
                    <el-button link type="primary" size="small" @click="handleClick(4 , scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <Pagination 
        :total="dataInfo.totalSize" 
        @changeHandler="changeHandler" />


        <!-- 用户添加 
        
        dialog添加v-if原因：在vue生命周期中，页面初始化的时候，
        mounted等一些生命周期钩子函数只会执行一次，关闭弹窗并没有销毁，
        所以不会再次执行；
        加上v-if后的作用就是在隐藏dialog的时候销毁这个dialog，把v-if设置为false可以直接讲其从DOM结构中删除。
        -->
        <el-dialog
        title="增加管理员"
        width="500"
        v-model="userDialog.add"
        v-if="userDialog.add"
        @close="closeHandle(1)">
            <UserAddDialog :roleData="roleData" @addResult="addResult" />
        </el-dialog>


        <!-- 用户编辑 -->
        <el-dialog
        title="编辑管理员"
        width="500"
        v-model="userDialog.edit"
        v-if="userDialog.edit"
        @close="closeHandle(2)">
            <UserEditDialog :roleData="roleData" :userInfo="dataInfo.userInfo" @editResult="editResult" />
        </el-dialog>


    </el-card>
</template>

<script>
// API
import { getUserPageList , modifyStatus } from "@/api/user"
import { getRoleList } from "@/api/role"

import { reactive } from 'vue';
import UserAddDialog from '@/views/permissionuser/components/UserAddDialog.vue'
import UserEditDialog from "@/views/permissionuser/components/UserEditDialog.vue";
import { getUserid } from '@/utils/cookies';

import Pagination from '@/components/pagination/index.vue'

export default {
    components: { UserAddDialog , UserEditDialog , Pagination },
    props: {},
    setup(props) {
        let userId = getUserid()

        const userDialog = reactive({
            add: false,
            edit: false
        })

        const handleClick = (flag , userData) => {
            if (flag == 1) {    // 增加
                console.log("角色数据：" , roleData)
                userDialog.add = true
            } else if (flag == 2) { // 编辑
                dataInfo.userInfo = userData
                userDialog.edit = true
            } else if (flag == 3) { // 禁用/启用
                modifyUserStatus(userData.userId)
            } else {
                // 删除
            }
        }

        const queryInfo = reactive({
            form: {
                // 用户名
                username: "",
                // 手机号
                phoneNumber: "",
                // email
                email: "",
                // 当前第多少页
                pageNum: 1,
                // 每页显示条数
                pageSize: 10,
            }
        })
        const dataInfo = reactive({
            userDataArray: [],
            userInfo: {},
            totalSize: 0
        })
        const getUserList = async () => {
            const { data: res } = await getUserPageList(queryInfo.form)
            // console.log("用户数据", res)
            dataInfo.totalSize = res.totalSize
            dataInfo.userDataArray = res.content
        }
        getUserList()


        // 获取角色列表
        let roleData = []
        const roleList = async () => {
            const { data: res } = await getRoleList()
            for (let role in res) {
                roleData.push(res[role])
            }
        }
        roleList()

        // 用户禁用/启用
        const modifyUserStatus = async (userId) => {
            const { data: res } = await modifyStatus(userId)
            getUserList()
        }

        const changeHandler = (type,num) => {
            console.log(type)
            console.log(num)
            if (type === 'sizechange') {
                queryInfo.form.pageSize = num
                queryInfo.form.pageNum = 1
            }
            if (type === 'currentchange') {
                queryInfo.form.pageNum = num
            }
            getUserList()
        }

        const closeHandle = (flag) => {
            if (flag == 1) {    // 关闭增加弹框
                userDialog.add = false
            }
            if (flag == 2) {    // 关闭编辑弹窗
                userDialog.edit = false
            }
        }


        /**
         * 用户添加结果
         */
        const addResult = (result) => {
            console.log("添加结果：" , result)
            if (result) {   // 成功添加
                // 关闭用户添加弹窗
                userDialog.add = false
                // 重新请求用户列表
                getUserList()
            }
        }

        /**
         * 用户编辑结果
         * result： 1.成功 2.取消
         */
        const editResult = (result) => {
            console.log("编辑结果：" , result)
            if (result === 1) {
                getUserList()
            } 
            userDialog.edit = false
        }




        return {
            handleClick,
            getUserList,
            closeHandle,
            roleList,
            addResult,
            editResult,
            changeHandler,
            dataInfo,
            queryInfo,
            userDialog,
            userId,
            roleData
        }
    }
}


</script>


<style lang="scss" scoped>

.card-bottom {
    height: 75px;
}
.width-160 {
    width: 160px;
}

.width-100 {
    width: 100px;
}

.width-180 {
    width: 180px;
}
</style>